﻿
var viewModel = new function () {
    this.LeadId = ko.observable(data.LeadId);
    this.LeadType = ko.observable(data.LeadTypeId);
    this.LeadTypeOptions = ko.observableArray(data.LeadType);
    this.LeadSource = ko.observable(data.LeadSourceId);
    this.LeadSourceOptions = ko.observableArray(data.LeadSource);
    this.UserId = ko.observable(data.UserId);
    this.OwnerId = ko.observable(data.OwnerId);
    this.UserOptions = ko.observableArray(data.UserFilter);
    this.IsAdmin = ko.observable(data.IsAdmin);

    // Add new requirement
    this.EnableLeadType = ko.computed(function () {
        return !(!this.LeadTypeOptions() || !this.LeadTypeOptions().length || this.LeadTypeOptions().length <= 1);
    }, this);
    this.PleaseMessage = ko.computed(function () {
        return (!this.EnableLeadType()) ? "Xin hãy chọn nguồn khách hàng để bật biểu mẫu dưới." : "";
    }, this);

    // Added Action
    this.StatusId = ko.observable(data.StatusId);
    this.StatusOptions = ko.observableArray(data.StatusFilter);
    this.StatusLogList = ko.observableArray(data.StatusLogList);
    this.Note = ko.observable("");
    this.CommitAction = function () {
        if ($('#actionComment').val() == "") {
            this.Note("");
            return;
        }

        var dataPost = { "id": this.LeadId(), "userId": this.UserId(), "statusId": this.StatusId(), "note": this.Note() };

        // Ajax request
        $.ajax({
            type: "POST",
            url: "/Lead/AddStatus",
            data: dataPost,
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                viewModel.StatusLogList(model.StatusLogList);
                if (model.Status != "") {
                    $('#status').text(model.Status);
                }
                $('#actionComment').val("");
            },
            error: function (xhr, status, error) {
                showPopupError();
            }
        });
    };

    // Added Appointment
    this.Duration = ko.observable(data.ListAppointment.ListDuration[0].ID);
    this.DurationOptions = ko.observableArray(data.ListAppointment.ListDuration);
    this.LeadCalendarItems = ko.observableArray(data.ListAppointment.ListAppointments);
    this.Subject = ko.observable("").extend({ required: { message: "Tiêu đề là bắt buộc"} });
    this.Date = ko.observable("").extend({ required: { message: "Ngày là bắt buộc"} }).extend({
        pattern: {
            message: 'Enter a valid Date',
            params: '^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/(19\\d\\d|(20)?[0-7][0-8])$'
        }
    });

    this.Time = ko.observable("").extend({ required: { message: "Thời gian là bắt buộc"} }).extend({
        pattern: {
            message: 'Enter a valid Start Time',
            params: '^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])? ([pa]m|[PA]M)$'
        }
    });
    this.Reminder = ko.observable("0 minutes");
    this.GroupUpdateShow = ko.observable(false);
    this.SetShow = ko.observable(true);
    this.AppointmentId = ko.observable(0);

    this.editLine = function (line) {
        $('#subject').val(line.Title);
        $('#date').val(line.StartDate);
        $('#time').val(line.StartTime);

        // Set duration / reminder
        $("#duration option[value='" + line.Duration + "']").attr("selected", "selected");
        $("#groupTime .center").text($("#duration option[value='" + line.Duration + "']").text());
        $('input:radio[name=reminder]').filter('[value="' + line.Reminder + '"]').attr('checked', true);

        // Knockout property
        viewModel.Subject(line.Title);
        viewModel.Date(line.StartDate);
        viewModel.Time(line.StartTime);
        viewModel.Duration(line.Duration);
        viewModel.Reminder(line.Reminder);
        viewModel.GroupUpdateShow(true);
        viewModel.SetShow(false);
        viewModel.AppointmentId(line.Id);

        // Set grayed line selected for edit
        $("ul#app-list li").each(function () {
            $(this).removeClass("line-selected");
        });
        $('#appointment' + line.Id).parents("li").addClass("line-selected");
    };

    this.DeleteAppointment = function () {
        var appId = $('#appointmentId').val();
        var dataPost = { "id": appId };
        var line;
        for (var i = 0; i < viewModel.LeadCalendarItems().length; i++) {
            if (viewModel.LeadCalendarItems()[i].Id == appId) {
                line = viewModel.LeadCalendarItems()[i];
                break;
            }
        }

        // Ajax request
        $.ajax({
            type: "POST",
            url: "/Lead/DeleteCalendar",
            data: dataPost,
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                if (typeof model != "undefined" && (model === "" || typeof model.Error == "undefined" || !model.Error)) {

                    viewModel.LeadCalendarItems.remove(line);
                    viewModel.AppointmentId(0);
                    $("#subject").val('');
                    $("#date").val('');
                    $("#time").val('');

                    // auto calculate height of all items
                    resizeAppointment();

                    // Close
                    // Refresh
                    $('.btn-x').set_action_tooltip({
                        width: 150,
                        offset_x: 14,
                        offset_y: -7,
                        cancel_class: 'btn btn-cancel-small left',
                        continue_class: 'btn btn-delete-small right'
                    });
                }
                else {
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {
                showPopupError();
            }
        });
        viewModel.GroupUpdateShow(false);
        viewModel.SetShow(true);
    };

    this.UpdateAppointment = function () {
        if ($("#subject").val() == '') {
            this.Subject('');
        }
        if ($("#date").val() == '') {
            this.Date('');
        }
        if ($("#time").val() == '') {
            this.Time('');
        }

        if (viewModel.errors().length == 0) {
            // Build a function to post data
            if (this.AppointmentId() > 0) {
                var dataPost = {
                    "id": this.AppointmentId(),
                    "leadId": this.LeadId(),
                    "userId": this.UserId(),
                    "subject": this.Subject(),
                    "startDate": this.Date(),
                    "startTime": this.Time(),
                    "duration": this.Duration(),
                    "reminder": this.Reminder()
                };

                // Ajax request
                $.ajax({
                    type: "POST",
                    url: "/Lead/EditCalendar",
                    data: dataPost,
                    dataType: "json",
                    success: function (model, textStatus, jqXHR) {
                        if (model && typeof model.ListAppointments != "undefined" && (typeof model.Error == "undefined" || !model.Error)) {

                            viewModel.LeadCalendarItems(model.ListAppointments);
                            // Set to default value
                            viewModel.AppointmentId(0);
                            viewModel.GroupUpdateShow(false);
                            viewModel.SetShow(true);

                            // auto calculate height of all items
                            resizeAppointment();

                            //Refresh
                            $('.btn-x').set_action_tooltip({
                                width: 150,
                                offset_x: 14,
                                offset_y: -7,
                                cancel_class: 'btn btn-cancel-small left',
                                continue_class: 'btn btn-delete-small right'
                            });
                        }
                        else {
                            showPopupError();
                        }
                    },
                    error: function (xhr, status, error) {
                        showPopupError();
                    }
                });
                // End Ajax
            }

            $("#subject").val('');
            $("#date").val('');
            $("#time").val('');
            $("#appointment .row").each(function () {
                $(this).find("input.text").removeClass("text-active");
            });
        }
        else {
            viewModel.errors.showAllMessages();
        }
    };

    this.CancelAppointment = function () {
        $("#subject").val("");
        $("#date").val("");
        $("#time").val("");
        viewModel.Duration(30);
        viewModel.Reminder("0 minutes");
        viewModel.AppointmentId(0);
        viewModel.GroupUpdateShow(false);
        viewModel.SetShow(true);
        $("ul#app-list li").each(function () {
            $(this).removeClass("line-selected");
        });
    };

    this.SetAppointment = function () {
        if ($("#subject").val() == '') {
            this.Subject('');
        }
        if ($("#date").val() == '') {
            this.Date('');
        }
        if ($("#time").val() == '') {
            this.Time('');
        }

        if (viewModel.errors().length == 0) {
            // Build a function to post data
            if (this.AppointmentId() <= 0) {
                var dataPost = {
                    "leadId": this.LeadId(),
                    "userId": this.OwnerId() != 0? this.OwnerId: this.UserId(),
                    "subject": this.Subject(),
                    "startDate": this.Date(),
                    "startTime": this.Time(),
                    "duration": this.Duration(),
                    "reminder": this.Reminder()
                };

                // Ajax request
                $.ajax({
                    type: "POST",
                    url: "/Lead/AddCalendar",
                    data: dataPost,
                    dataType: "json",
                    success: function (model, textStatus, jqXHR) {
                        if (model && typeof model.ListAppointments != "undefined" && (typeof model.Error == "undefined" || !model.Error)) {

                            viewModel.LeadCalendarItems(model.ListAppointments);
                            // Set to default value
                            viewModel.AppointmentId(0);
                            viewModel.GroupUpdateShow(false);
                            viewModel.SetShow(true);

                            // auto calculate height of all items
                            resizeAppointment();

                            // Refresh
                            $('.btn-x').set_action_tooltip({
                                width: 150,
                                offset_x: 14,
                                offset_y: -7,
                                cancel_class: 'btn btn-cancel-small left',
                                continue_class: 'btn btn-delete-small right'
                            });
                        }
                        else {
                            showPopupError();
                        }
                    },
                    error: function (xhr, status, error) {
                        showPopupError();
                    }
                });
                // End Ajax
            }

            $("#subject").val('');
            $("#date").val('');
            $("#time").val('');
            $("#appointment .row").each(function () {
                $(this).find("input.text").removeClass("text-active");
            });
        }
        else {
            viewModel.errors.showAllMessages();
        }
    };
};

// Apply view model
viewModel.errors = ko.validation.group(viewModel);
ko.applyBindings(viewModel, document.getElementById("main"));


$(document).ready(function () {
	$('#groupfields ul').hide();
	$('#groupfields ul:first').show();
	$('#grouptab span:first').addClass('current');
	$('#grouptab span a').click(function () {
		// Focus current tab
		$('#grouptab span').removeClass('current');
		$(this).parent().addClass('current');

		// Show current group
		var currentTab = $(this).attr('href');
		$('#groupfields ul').hide();
		$(currentTab).show();

		return false;
	});

	// Lead activity
	$('div.form-table').hide();
	$('div.form-table:first').show();
	$('#groupActivity span:first').addClass('current');
	$('#groupActivity span a').click(function () {
		// Focus current tab
		$('#groupActivity span').removeClass('current');
		$(this).parent().addClass('current');

		// Show current group
		var currentTab = $(this).attr('href');
		$('div.form-table').hide();
		$(currentTab).show();

		if (currentTab == "#appointment") {
			resizeAppointment();
		}
		else {
			resizeAction();
		}
		return false;
	});

	// Collspan/ Expand
	$('ul.accordeon-tabs li').each(function () {
		$(this).find(".tab").click(function () {
			if ($(this).parent().attr("class") == "open") {
				$(this).parent().removeClass("open");
				$(this).parent().addClass("close");
				$(this).parent().find(".panel").css("display", "none");
			}
			else {
				$(this).parent().removeClass("close");
				$(this).parent().addClass("open");
				$(this).parent().find(".panel").css("display", "block");
			}
		});
	});

	// Set time
	var nowDate = new Date();
	$(".calendar-date").datepicker();
	$(".calendar-time").timepicker();
	$(".start-time").timepicker({ hour: nowDate.getHours(), minute: nowDate.getMinutes() });
	$(".calendar-datetime").datetimepicker();
	$(".cal").datepicker();

	// Hide model
	$('.fancybox-wrap').hide();
	resizeAction();
});


// Change position for 2 action edit|delete
// auto scale height when display a scroll
$(window).resize(function () {
	resizeAction();
	resizeAppointment();
});

function resizeAppointment() {
	var height = 0;
	$('#app-list LI').each(function () {
		height += $(this).height() + 15;
	});

	// Set position for 2 acts
	if (height > 150) {
		$('#app-list LI').each(function () {
			if (!is_ie8) {
				$(this).find('.col2').attr("style", "margin-left:0px");
				$(this).find('.colact').attr("style", "margin-left:0px");
			}
			else {
				$(this).find('.col2').attr("style", "margin-left:3px");
				$(this).find('.colact').attr("style", "margin-left:5px");
			}
		});
	}
	else {
		$('#app-list LI').each(function () {
			if (!is_ie8) {
				$(this).find('.col2').attr("style", "margin-left:-5px");
				$(this).find('.colact').attr("style", "margin-left:-10px");
			}
			else {
				$(this).find('.col2').attr("style", "margin-left:-2px");
				$(this).find('.colact').attr("style", "margin-left:-5px");
			}
		});
	}
}

function resizeAction() {
	var height = 0;
	$('#action-list LI').each(function () {
		height += $(this).height() + 15;
	});

	// Set position for 2 acts
	if (height > 150) {
		$('#action-list LI').each(function () {
			if (!is_ie8) {
				$(this).find('.col2').attr("style", "margin-left:0px");
				$(this).find('.col3').attr("style", "margin-left:0px");
			}
			else {
				$(this).find('.col2').attr("style", "margin-left:2px");
				$(this).find('.col3').attr("style", "margin-left:5px");
			}
		});
	}
	else {
		$('#action-list LI').each(function () {
			if (!is_ie8) {
				$(this).find('.col2').attr("style", "margin-left:-5px");
				$(this).find('.col3').attr("style", "margin-left:-4px");
			}
			else {
				$(this).find('.col2').attr("style", "margin-left:-2px");
				$(this).find('.col3').attr("style", "margin-left:0px");
			}
		});
	}
}

function closePopup() {
	$('#popup').hide();
	$('#fancybox-overlay').hide();
}

//$("form").validate({ submitHandler: viewModel.Submit });
$(document).ready(function() {
	$("form#myForm").validation();
});

// We can check if the form is valid on demand, using our validate function
function preValidateLeadForm(inp) {
	var $form = $(inp).closest("form");

	// Lead Type and Lead Source are required
	var isValid = false,
		leadTypeId = parseInt($form.find("#toolbargroup .sel-lead-type input[name='LeadTypeId']").val()),
		leadSourceId = parseInt($form.find("#toolbargroup .sel-lead-source select:first").val());

	if (!isNaN(leadSourceId) && leadSourceId > 0) {

		if (!$form.find("#toolbargroup .sel-lead-type select:first option").length
			|| (!isNaN(leadTypeId) && leadTypeId > 0)) {

			isValid = true;
		}
	}

	if (isValid) {
		var groupErrorMessage = $form.find('#errorMessages');

		if ($form.validate()) {
			groupErrorMessage.hide();
			$(".fancybox-skin, #fancybox-overlay").show();

			$.fancybox($("#popup-sumitting"), {
				padding: 0,
				closeBtn: false,
				helpers: {
					overlay: {
						opacity: 0.6,
						css: {
							'background-color': '#11619D'
						}
					}
				},
				beforeClose: function () {
					return false;
				}
			});

			return true;
		}
		else {
			// Add Error
		    groupErrorMessage.find(".errorgrid").html('<strong>Lỗi: Dữ liệu không hợp lệ</strong><span>Mẫu đơn này đã không được lưu, hãy sửa chữa các lỗi sau đây:<br /></span><ul class="errorlist" style="margin-top:10px; margin-left:20px"></ul>');

			// Find error message
			$form.find("#grouptab a.nexttab").each(function() {
				var $lnk = $(this),
					tabName = $lnk.text();

				$("ul" + $lnk.attr("href").replace(/^.*?#+/g, "#") + " li").each(function() {
					$(this).find(".error-desc").each(function() {
						groupErrorMessage.find(".errorlist").append("<li>" + tabName + " &raquo; " + $(this).html() + "</li>");
					});
				});
			});

			groupErrorMessage.show();
		}
	}

	return false;
}

// Show tooltip delete appointment
$(function() {
	$('.btn-x').set_action_tooltip({
		width: 150,
		offset_x: 14,
		offset_y: -7,
		cancel_class: 'btn btn-cancel-small left',
		continue_class: 'btn btn-delete-small right'
	});
});
// END

function OpenPrintLeadWindow() {
	var url = "/Lead/PrintLead/" + data.LeadId,
		widthPopup = 968,
		heightPopup = 500,
		leftPopup = (screen.width / 2) - (widthPopup / 2),
		topPopup = (screen.height / 2) - (heightPopup / 2);

	window.open(url, '', 'left=' + leftPopup + ',top=' + topPopup + ',width=' + widthPopup + ',height=' + heightPopup + ',scrollbars=yes,toolbar=0,status=0');
}
